package com.czx.interceptor;

import com.czx.common.constants.CookieKey;
import com.czx.common.security.UserTokenThreadLocal;
import com.czx.service.UserTokenService;
import com.czx.common.utils.CookieUtils;
import com.czx.vo.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserTokenInceptor implements HandlerInterceptor {
    @Autowired
    private UserTokenService userTokenService;
    /**
     * conroller之前被调用
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1.先从Cookie中获取uuid
        String uuid = CookieUtils.getValue(CookieKey.LOGIN_COOKIE_KEY);

        // 2.判断是否有
        if (!ObjectUtils.isEmpty(uuid)) {
            // 能进来他登陆过
            UserToken userToken = userTokenService.getUserToken(uuid);
            if (userToken != null) {
                // 它的token还是有有效的,然后保存到threadlocal中
                UserTokenThreadLocal.set(userToken);
            }
        }
        return true;
    }

    // controller调用之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserToken userToken = UserTokenThreadLocal.get();
        UserTokenThreadLocal.remove();
        if (modelAndView != null && userToken != null) {
            modelAndView.addObject("loginUser", userToken);
        }
    }

    // 视图渲染之后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}

